package com.yxq.mdt.app.modules.socialcontact.ui.activity;

import android.media.AudioManager;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.hyphenate.chat.EMCallStateChangeListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.EMNoActiveCallException;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.media.EMCallSurfaceView;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.glide.GlideHelper;
import com.yxq.mdt.app.modules.personal.bean.MyPersonalBean;
import com.yxq.mdt.app.modules.personal.model.UserModel;
import com.yxq.mdt.app.modules.socialcontact.model.LiveModel;
import com.yxq.mdt.app.modules.socialcontact.presenter.ILiveContract;
import com.yxq.mdt.app.modules.socialcontact.presenter.LivePresenter;
import com.yxq.mdt.app.modules.withdraw.bean.WithDrawResultBean;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.PhoneStateManager;
import com.yxq.mdt.app.utils.StringUtils;
import com.yxq.mdt.app.widgets.CircleImageView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 语音接受方
 */
public class VoiceTakeChatActivity extends CallActivity<LivePresenter> implements ILiveContract.View {
    @BindView(R.id.opposite_surface)
    EMCallSurfaceView oppositeSurface;
    @BindView(R.id.local_surface)
    EMCallSurfaceView localSurface;
    @BindView(R.id.local_surface_image)
    CircleImageView localSurfaceImage;
    @BindView(R.id.btn_answer)
    ImageView btnAnswer;
    @BindView(R.id.btn_refuse)
    ImageView btnRefuse;
    @BindView(R.id.layout_surface_container)
    RelativeLayout layoutSurfaceContainer;
    protected EMCallStateChangeListener callStateListener; //通话状态监听器
    @BindView(R.id.video_tv_nick_name)
    TextView videoTvNickName;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.btn_end_call)
    ImageView btnEndCall;
    @BindView(R.id.open_chat_rel_online)
    RelativeLayout openChatRelOnline;
    // 视频通话画面显示控件，这里在新版中使用同一类型的控件，方便本地和远端视图切换
    private int surfaceState = -1;
    private String from;
    CountDownTimer countDownTimer;
    String userId;
    private boolean isMuteState;
    private boolean isHandsfreeState;

    @Override
    public int getLayoutId() {
        setStatusBarDarkFont(false);
        setEnableImmersion(true);
        setStatusBarColor(R.color.black);
        return R.layout.activity_take_voice_chat;
    }
    @Override
    public void onBackPressed() {

    }
    @Override
    public void initView() {
        super.initView();
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

        localSurface.setZOrderMediaOverlay(true);
        localSurface.setZOrderOnTop(true);

        //设置Surface
        EMClient.getInstance().callManager().setSurfaceView(localSurface, oppositeSurface);

        from = getIntent().getStringExtra("from");

        new Handler().postDelayed(() -> addCallStateListener(), 500);

    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter = new LivePresenter(this, new LiveModel());
        userId = from.replaceAll("yxq", "");
        UserModel.getGaUserExtVoById(userId, new ApiModel.CommonCallback<MyPersonalBean>() {
            @Override
            public void onSuccess(MyPersonalBean myPersonalBean) {
                if (myPersonalBean != null) {
                    if (myPersonalBean.getGsName() != null) {
                        videoTvNickName.setText(myPersonalBean.getGsName());
                    }
                    GlideHelper.load(mActivity, myPersonalBean.getHeadimg(), localSurfaceImage);
                }
            }

            @Override
            public void onError(String errMsg) {

            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    break;
                case 2:
                    findViewById(R.id.open_chat_rel_online).setVisibility(View.VISIBLE);
//                    openSpeakerOn();
                    startTimer();
                    // Start to watch the phone call state.
                    PhoneStateManager.get(VoiceTakeChatActivity.this).addStateCallback(phoneStateCallback);
                    break;
                case 3:
                    PhoneStateManager.get(VoiceTakeChatActivity.this).removeStateCallback(phoneStateCallback);
                    removeCallStateListener();
                    finish();
                    break;
            }
        }
    };

    void removeCallStateListener() {
        EMClient.getInstance().callManager().removeCallStateChangeListener(callStateListener);
    }

    int time = 0;

    private void startTimer() {
        countDownTimer = new CountDownTimer(Long.MAX_VALUE, 1000) {
            @Override
            public void onTick(long l) {
                time++;
                TextView tvTime = findViewById(R.id.tv_time);
                tvTime.setText(StringUtils.formatTime(time));
            }

            @Override
            public void onFinish() {

            }
        };
        countDownTimer.start();
    }

    /**
     * 挂断
     */
    public void newEndCall() {
        try {
            EMClient.getInstance().callManager().endCall();
        } catch (EMNoActiveCallException e) {
            e.printStackTrace();
        } finally {
            finish();
        }
    }

    /**
     * 接听通话
     */
    public void answerCall() {

        try {
            EMClient.getInstance().callManager().answerCall();
        } catch (EMNoActiveCallException e) {
            e.printStackTrace();
        }

    }

    /**
     * 拒绝接听
     */
    public void refuseCall() {
        /**
         * 拒绝接听
         * @throws EMNoActiveCallException
         */
        try {
            EMClient.getInstance().callManager().rejectCall();
            finish();
        } catch (EMNoActiveCallException e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.btn_answer, R.id.btn_refuse, R.id.btn_end_call, R.id.iv_mute, R.id.iv_handsfree})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_answer:
                //接受
//                openSpeakerOn();
                if (ringtone != null)
                    ringtone.stop();
                answerCall();
                break;
            case R.id.btn_refuse:
                //拒接
                refuseCall();
                break;
            case R.id.btn_end_call:
                //挂断
                newEndCall();
                break;
            case R.id.iv_mute:
                //静音
                if (isMuteState) {
                    ImageView muteImage = findViewById(R.id.iv_mute);
                    muteImage.setImageResource(R.mipmap.em_icon_mute_normal);
                    try {
                        EMClient.getInstance().callManager().resumeVoiceTransfer();
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    }
                    isMuteState = false;
                } else {
                    ImageView muteImage = findViewById(R.id.iv_mute);
                    muteImage.setImageResource(R.mipmap.em_icon_mute_on);
                    try {
                        EMClient.getInstance().callManager().pauseVoiceTransfer();
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    }
                    isMuteState = true;
                }
                break;
            case R.id.iv_handsfree:
                //扬声器
                if (isHandsfreeState) {
                    ImageView handsFreeImage = findViewById(R.id.iv_handsfree);
                    handsFreeImage.setImageResource(R.mipmap.em_icon_speaker_normal);
                    closeSpeakerOn();
                    isHandsfreeState = false;
                } else {
                    ImageView handsFreeImage = findViewById(R.id.iv_handsfree);
                    handsFreeImage.setImageResource(R.mipmap.em_icon_speaker_on);
                    openSpeakerOn();
                    isHandsfreeState = true;
                }
                break;
        }
    }

    private void addCallStateListener() {
        callStateListener = new EMCallStateChangeListener() {
            @Override
            public void onCallStateChanged(CallState callState, CallError callError) {
                switch (callState) {
                    case CONNECTING: // 正在连接对方
                        break;
                    case CONNECTED: // 双方已经建立连接
                        mHandler.sendEmptyMessage(1);
                        break;
                    case ACCEPTED: // 电话接通成功
                        mHandler.sendEmptyMessage(2);
                        break;
                    case DISCONNECTED: // 电话断了
                        mHandler.sendEmptyMessage(3);
                        break;
                    case NETWORK_UNSTABLE: //网络不稳定
                        if (callError == CallError.ERROR_NO_DATA) {
                            //无通话数据
                        } else {
                        }
                        break;
                    case NETWORK_NORMAL: //网络恢复正常
                        break;
                    default:
                        break;
                }

            }
        };
        EMClient.getInstance().callManager().addCallStateChangeListener(callStateListener);

        //声音提示
        Uri ringUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
        audioManager.setMode(AudioManager.MODE_RINGTONE);
        audioManager.setSpeakerphoneOn(true);
        ringtone = RingtoneManager.getRingtone(this, ringUri);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            ringtone.setLooping(true);
        }
        ringtone.play();
    }

    PhoneStateManager.PhoneStateCallback phoneStateCallback = new PhoneStateManager.PhoneStateCallback() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:   // 电话响铃
                    break;
                case TelephonyManager.CALL_STATE_IDLE:      // 电话挂断
                    // resume current voice conference.
                    if (isMuteState) {
                        try {
                            EMClient.getInstance().callManager().resumeVoiceTransfer();
                        } catch (HyphenateException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:   // 来电接通 或者 去电，去电接通  但是没法区分
                    // pause current voice conference.
                    if (!isMuteState) {
                        try {
                            EMClient.getInstance().callManager().pauseVoiceTransfer();
                        } catch (HyphenateException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        newEndCall();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        super.onDestroy();
    }

    @Override
    public void onLoadLiveSuccess(int status, String result) {

    }

    @Override
    public void onLoadLiveFailed(String err) {

    }

    @Override
    public void onCommentSuccess(WithDrawResultBean result) {

    }

    @Override
    public void onCommentFailed(String err) {

    }
}
